<template>
	<view>
		<view class="mask" v-if="playshow"></view>
		<view class="modal" :class="[playshow?'modal-show':'modal-hidden']">
			<image class="close-model" src="/static/close.png" @click="closeModel" mode="widthFix"></image>
			<view class="money-list-box">
				<view class="money-order-content">
					<view class="order-list">
						<text class="order-on">订单编号:</text>
						<text class="order-info">{{ordersn}}</text>
					</view>
				</view>
			</view>
			<view class="money-list-box">
				<view class="money-list-content">
					<view class="money-list-type" @click="radioValue='yue'">
						<view class="money-list-left">
							<view class="money-list-icon">¥</view>
							<view class="money-list-text">鸡蛋券支付</view>
							<view class="money-list-my">余额:¥{{credit2?credit2:0.00}}</view>
						</view>
						<radio value="yue" color="#c5000b" :checked='radioValue == "yue"' />
						</radio>
					</view>
					<!-- <view class="money-list-type" @click="radioValue='ysf'">
						<view class="money-list-left">
							<image src="/static/images/mine/ysf.png" class="money-list-image"></image>
							<view class="money-list-text">云闪付支付</view>
						</view>
						<radio value="ysf" color="#c5000b" :checked='radioValue == "ysf"' />
						</radio>
					</view> -->
					<!-- <view class="money-list-type" @click="radioValue='yi_pay_weixin'">
						<view class="money-list-left">
							<image src="/static/wx.png" class="money-list-image"></image>
							<view class="money-list-text">微信支付</view>
						</view>
						<radio value="yi_pay_weixin" color="#c5000b" :checked='radioValue == "yi_pay_weixin"' />
						</radio>
					</view> -->
				</view>
			</view>
			
			<view style="padding:90rpx 30rpx 30rpx 30rpx;">
				<u-button type="primary" shape="circle"
					:custom-style="{backgroundColor: background,color: color,height: '90rpx',}" @click="allPay()">立即支付
				</u-button>
			</view>
		</view>
		

		<u-modal v-model="showSuccess" show-cancel-button confirm-color="#666 !important" title="订单支付成功"
			:title-style="{fontWeight: '700', fontSize: '36rpx'}"
			:content-style="{fontWeight: '700', fontSize: '56rpx', color: '#30549C'}" :content="`￥${price}`"
			confirm-text="返回首页" cancel-text="查看订单" @confirm="$u.route({type: 'tab', url: '/pages/home/home'})"
			@cancel="cancel"></u-modal>
	</view>
</template>

<script>
	var timer;
	const hxruppay = uni.requireNativePlugin('HXR-UPPay')
	export default {
		props: {
			orderid: {
				type: String,
				default: ''
			},
			background: {
				type: String,
			 default: '#001b4d'
			},
			color: {
				type: String,
				default: '#ffffff'
			},
			playshow: {
				type: Boolean,
				default: false
			},
			closeBack:{
				type:Function,
				default:function(){
					return;
				}
			}
		},
		data() {
			return {
				obj: {},
				res: [],
				ordersn: '',
				price: '',
				str: '',
				credit2: '',
				fuxiao: '',
				duli: '',
				openid: "",
				openid1: '',
				title: '',
				chongzhi: '',
				merchid: '',
				merch_credit2: '',
				jfdk: '',
				yiqian_coupon: '',
				isWeixin: '',

				showZhifu: false,
				ids: {},
				cd_shop_id: '',
				radioValue: 'yue',
				showSuccess: false,
			};
		},
		onLoad: function(e) {
			// #ifdef  H5
			this.isWeixin = navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1
			// #endif
			// uni.showLoading()
			if (this.orderid && this.playshow) {
				this.$GetOpenid().then(res => {
					clearTimeout(timer)
					this.openid = res;
					this.setAjax()
					this.getArguments()
				})
			}
		},
		watch: {
			playshow: function(val, old) {
				if (val == false) {
					clearTimeout(timer);
					return;
				}
				if (val && this.orderid) {
					this.$GetOpenid().then(res => {
						clearTimeout(timer)
						this.openid = res;
						this.setAjax()
						this.getArguments()
					})
				}
			},
		},
		onShow() {
			console.log('this.orderid', this.orderid);
		},
		onHide() {
			clearTimeout(timer)
		},
		onUnload() {
			clearTimeout(timer)
		},
		methods: {
			closeModel(){
				this.closeBack()
			},
			cancel(){
				uni.reLaunch({
					url:'/pages/order/order?index=2'
				})
			},
			allPay() {
				if (!this.radioValue) return this.$u.toast('请选择支付方式')
				// 买入单
				if (this.radioValue == 'mrd') return this.cangdanzhifu();
				// 余额
				if (this.radioValue == 'yue') return this.submit()
				// 翼支付微信
				if (this.radioValue == 'yi_pay_weixin') return this.yi_pay('weixin')
				// 翼支付支付宝
				if (this.radioValue == 'yi_pay') return this.yi_pay()
				// 云闪付支付
				if (this.radioValue == 'ysf') return this.yi_pay()
			},
			async cangdanzhifu() {
				this.showZhifu = true
				let res = await this.$myRequest({
					url: '/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=api.index.can_buy_id&app=1',
					data: {
						openid: uni.getStorageSync('openid')
					}
				})
				console.log('查看ids', res)
				this.ids = res.data
			},
			submit() {
				if (Number(this.credit2) < this.price) {
					uni.showModal({
						content: "余额不足",
						confirmText: "确定",
					})
					return
				}
				uni.showModal({
					content: "确认要支付吗？",
					confirmText: "确定",
					cancelText: "取消",
					success: res => {
						if (res.confirm) {
							uni.request({
								url: this.$BASE_URL +
									'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.complete&app=1',
								method: 'POST',
								data: {
									openid: this.openid,
									id: this.orderid,
									type: 'credit',
								},
								header: {
									'Content-Type': 'application/x-www-form-urlencoded'
								},
								success: res => {
									uni.request({
										url: this.$BASE_URL +
											'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.complete&app=1',
										method: 'POST',
										data: {
											openid: this.openid,
											id: this.orderid,
											type: 'credit',
										},
										header: {
											'Content-Type': 'application/x-www-form-urlencoded'
										},
										success: res => {
											if (res.data.status == 1) {
												this.showSuccess = true
											}else{
												uni.showToast({
													title: res.data.result.message,
													icon: 'none'
												})
											}
										},
										fail: () => {},
										complete: () => {}
									});
								},
								fail: () => {},
								complete: () => {}
							});
						}
					},
				})
			},
			async yi_pay(type = 'yi_pay') {
				let res = await this.$myRequest({
					url: `/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=api.index.${type == 'weixin' ? 'yi_pay_wechat' : 'yi_pay'}&app=1`,
					method: 'post',
					data: {
						openid: uni.getStorageSync('openid'),
						goodstitle: this.title,
						total_amount: this.price,
						out_trade_no: this.ordersn,
					}
				})
				console.log(res)
				let success1 = res.data.indexOf('success') + 9
				let success2 = res.data.indexOf('payinfo') - 3
				let isSuccess = res.data.substring(success1, success2)

				if (isSuccess != 'true') return this.$u.toast('支付失败')

				let index1 = res.data.indexOf('paymentUrl') + 13
				let index2 = res.data.indexOf('thirdOrderNo') - 3
				let href = res.data.substring(index1, index2)
				// &tradeAmt=0.01&payTool=ALIPAY#/mixpay
				// let alipay = `alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=${href}&tradeType=ALIPAY`
				console.log(href)
				// #ifdef  H5
				window.location.href = href
				// #endif

				// #ifdef APP-PLUS
				plus.runtime.openURL(href)
				// #endif
			},
			setAjax() {
				uni.request({
					url: this.$BASE_URL + '/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay&app=1',
					method: 'POST',
					data: {
						'openid': this.openid,
						'id': this.orderid
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: res => {
						if (res.data.error == 0) {
							this.$u.toast(res.data.message)
							setTimeout(() => {
								clearInterval(timer)
								this.$u.route({
									type: 'tab',
									url: '/pages/mine/mine'
								})
							}, 1500)
							return
						}
						console.log('获取数据', res)
						uni.hideLoading()
						this.ordersn = res.data.order.ordersn
						this.openid1 = res.data.member.openid1
						this.openid = res.data.member.openid
						this.fuxiao = res.data.member.fuxiao
						this.yiqian_coupon = res.data.member.yiqian_coupon
						this.duli = res.data.member.duli
						this.jfdk = res.data.order.jfdk
						this.title = res.data.title
						this.res = res.data
						this.merchid = res.data.merchid
						this.chongzhi = res.data.chongzhi
						this.merch_credit2 = res.data.merch_credit2
						this.jfdk = res.data.order.jfdk
						this.str = '<p style="text-align: right;color: #30549C;">' + res.data.str + "</p>"
						if (res.data.ispeerpay != '' && res.data.ispeerpay != false) {
							this.price = res.data.peerprice.toFixed(2)
						} else {
							this.price = res.data.order.price.toFixed(2)
						}
					},
					fail: () => {},
					complete: () => {}
				});
				
				this.$myRequest({
					url: `/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=member.eggcommunity&app=1&type=1`,
					method:'POST',
					data:{openid:this.openid}
				}).then(res=>{
					this.credit2 = Number(res.data.egg_num_26).toFixed(2)
				})
			},
			async getArguments() {
				let {
					data
				} = await this.$myRequest({
					url: '/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=api.index.order_check&app=1',
					data: {
						order_sn: this.ordersn
					}
				})
				console.log('订单sn', this.ordersn, data)
				// #ifdef APP-PLUS
				// if (plus.runtime.arguments == 'wechat') {
				if (data.status == 1) {
					clearTimeout(timer)
					this.showSuccess = true
				}
				// #endif

				if (data.status != 1) {
					clearTimeout(timer)
					timer = setTimeout(() => this.getArguments(), 2000)
				}
			},
			wxh5pay: function() {
				if (this.openid1 == '' || this.openid1 == null) {
					let oppid = this.openid
					uni.showModal({
						title: '提示',
						content: '微信支付授权',
						success: function(res) {
							if (res.confirm) {
								window.location.href =
									this.$BASE_URL +
									'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.jspay.getOpenid&openid=' +
									oppid
								uni.showToast({
									title: '授权成功请支付',
									icon: 'none'
								})
							} else {
								console.log('用户点击取消')
							}
						}
					});
				} else {
					uni.request({
						url: this.$BASE_URL +
							'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.jspay&app=1', // 正常支付流程
						method: 'GET',
						data: {
							'openid': this.openid1,
							'SetBody': this.title,
							'trade_no': this.ordersn,
							'Total_fee': this.price
						},
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: res => {
							this.obj = res.data
							this.jsApiCall()
						},
						fail: () => {},
						complete: () => {}
					})
				}
			},
			submit_sh() {
				var that = this
				if (Number(this.chongzhi) == 1) {
					uni.showModal({
						content: "余额不足,请充值",
						confirmText: "确定",
						showCancel:false
					})
					return
				}
				uni.showModal({
					content: "确认要支付吗？",
					confirmText: "确定",
					cancelText: "取消",
					success: res => {
						if (res.confirm) {
							uni.request({
								url: this.$BASE_URL +
									'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.complete&app=1',
								method: 'POST',
								data: {
									openid: this.openid,
									id: this.orderid,
									type: 'merch_credit2',
								},
								header: {
									'Content-Type': 'application/x-www-form-urlencoded'
								},
								success: res => {
									uni.request({
										url: this.$BASE_URL +
											'/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.complete&app=1',
										method: 'POST',
										data: {
											openid: this.openid,
											id: this.orderid,
											type: 'merch_credit2',
										},
										header: {
											'Content-Type': 'application/x-www-form-urlencoded'
										},
										success: res => {
											uni.navigateTo({
												url: 'success/success?id=' +
													this.orderid + '&result=' +
													res.data.result
													.result
											});
											setTimeout(function() {
												uni.showModal({
													content: "支付成功",
													confirmText: "确定",
												})
											}, 1000);
										},
										fail: () => {},
										complete: () => {}
									});
								},
								fail: () => {},
								complete: () => {}
							});
						}
					},
				})
			},
			async ad_pay_ysf() {
				let res = await this.$myRequest({
					url: '/index.php?i=4&c=entry&m=ewei_shopv2&do=mobile&r=api.index.credit_ad_pay_ysf&app=1',
					method: 'post',
					data: {
						openid: uni.getStorageSync('openid'),
						num: this.price,
					}
				})
				console.log(res.data)
				if (res.data.error == 1) return this.$u.toast(res.data.message)
				this.ad_pay_ysfback(res.data.expend.pay_info)
			},
			ad_pay_ysfback(tn) {
				let that = this
				////安卓只会取 tn 和mode字段
				hxruppay.payWithData({
					'tn': tn,
					// 'schemeStr': '商户自定义协议，商户在调用支付接口完成支付后，用于引导支付控件返回而定义的协议',
					'mode': '00'
				}, res => {
					console.log('====res:' + JSON.stringify(res));
					if (res.status == 'cancel') {
						that.$u.toast('用户已取消云闪付支付')
					} else if (res.status == 'needCheck') {
						that.$u.toast('云闪付支付成功')
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/mine/mine'
							})
						}, 2000)
					}
				});
			},
			jsApiCall: function() {
				let orderid = this.orderid
				WeixinJSBridge.invoke( // 调起微信支付
					'getBrandWCPayRequest',
					this.obj,
					function(res) {
						// 根据状态改跳转状态
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							uni.navigateTo({
								url: './success/success?id=' + orderid
							});
						}
					}
				);
			}
		},
		destroyed() {
			clearTimeout(timer)
		}
	}
</script>

<style lang="scss">
	page {
		height: 100vh;
		background-color: #f2f5fa;
	}

	.list {
		padding: 20upx 24upx;
		border-top: 1px solid #e4e4e4;
		background: #fff;
	}

	.list .left {
		color: #666;
	}

	.money-box {
		padding: 0 30rpx;
		position: relative;

		.money-box-item {
			padding: 40rpx 0;
			background: url('') center no-repeat;
			background-size: 100% 100%;

			.money-item-num {
				font-size: 50rpx;
				font-weight: bold;
				color: #fff;
				text-align: center;
			}

			.money-item-text {
				font-size: 24rpx;
				text-align: center;
				color: #fff;
			}
		}
	}

	.money-list-box {
		.money-list-content {
			background-color: #fff;
			padding: 0 30rpx;

			.money-list-type {
				display: flex;
				padding: 30rpx 0;
				align-items: center;
				justify-content: space-between;
			}

			.money-list-border {
				border-bottom: 1px solid #fafafa;
			}

			.money-list-left {
				display: flex;
				align-items: center;
			}

			.money-list-icon {
				width: 70rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 50rpx;
				color: #ffffff;
				background-color: #c5000b;
				border-radius: 50%;
			}

			.money-list-text {
				font-size: 32rpx;
				font-weight: bold;
				margin-left: 30rpx;
			}

			.money-list-my {
				font-size: 30rpx;
				font-weight: bold;
				margin-left: 30rpx;
			}

			.money-list-image {
				width: 70rpx;
				height: 70rpx;
			}

			.money-list-change {
				width: 40rpx;
				height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: #fff;
				border-radius: 50%;
			}

			.money-list-change-import {
				border: 1px solid #eee;
				background-color: #fff;
			}

			.money-list-change-active {
				border: 1px solid #c5000b;
				background-color: #c5000b;
			}
		}
	}

	.money-order-content {
		background-color: #fff;
		padding: 30rpx;

		.order-title {
			padding-bottom: 20rpx;
			font-size: 32rpx;
			font-weight: bold;
		}

		.order-list {
			display: flex;
			font-size: 24rpx;
			align-items: center;

			.order-on {
				color: #888;
			}

			.order-price {
				color: #c5000b;
			}
		}
	}
	.mask{
		position: absolute;
		top:0;
		left:0;
		bottom:0;
		right:0;
		z-index: 300;
		background-color: rgba(0,0,0,.4);
	}
	.modal{
		position: absolute;
		width: 100%;
		z-index: 400;
		left: 0;
		bottom: 0;
		padding-top:60rpx;
		transition-duration: 400ms;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
	}
	.modal-show{
		transform: translateY(0);
	}
	.modal-hidden{
		transform: translateY(100%);
	}
	.close-model{
		position: absolute;
		top:10rpx;
		right:20rpx;
		width: 60rpx;
	}
</style>